/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.cfg.listener;

import cn.easyplatform.cfg.EngineConfiguration;
import cn.easyplatform.i18n.I18N;
import cn.easyplatform.spi.listener.ApplicationListener;
import cn.easyplatform.spi.listener.event.AppEvent;
import cn.easyplatform.spi.listener.event.Event;
import cn.easyplatform.utils.JmsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;
import java.io.Serializable;
import java.util.Locale;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class JmsApplicationListener implements ApplicationListener, ExceptionListener {

    private final static Logger log = LoggerFactory.getLogger(JmsApplicationListener.class);

    private ConnectionFactory connectionFactory;

    private Connection connection;

    private Session session;

    public JmsApplicationListener(EngineConfiguration engineConfiguration) {
        connectionFactory = JmsUtils.createConnectionFactory(engineConfiguration.getAttributes("jms").entrySet());
    }

    @Override
    public void publish(String projectId, String topic, Serializable msg, String... toUsers) {
        if (log.isDebugEnabled())
            log.debug("publish message {},{},{},{}", projectId, topic, toUsers, msg);
        MessageProducer producer = null;
        try {
            producer = create(topic);
            ObjectMessage message = session.createObjectMessage();
            message.setStringProperty("pid", projectId);
            if (toUsers.length > 0) {
                if (msg instanceof Event)
                    message.setObject(msg);
                else
                    message.setObject(new AppEvent(topic, msg));
                if (toUsers.length == 1)
                    message.setStringProperty("uid", toUsers[0]);
                else {
                    StringBuilder sb = new StringBuilder();
                    int iMax = toUsers.length - 1;
                    for (int i = 0; i <= iMax; i++) {
                        sb.append(toUsers[i]);
                        if (i < iMax)
                            sb.append(",");
                    }
                    message.setStringProperty("uid", sb.toString());
                }
            } else message.setObject(msg);
            producer.send(message);
        } catch (JMSException e) {
            if (log.isErrorEnabled())
                log.error("publish message", e);
            throw new RuntimeException(I18N.getLabel("easyplatform.message.publish.error", e.getMessage()));
        } finally {
            try {
                producer.close();
            } catch (JMSException e) {
            }
        }
    }

    @Override
    public void send(String projectId, String topic, Serializable msg, String... toUsers) {
        if (log.isDebugEnabled())
            log.debug("send message {},{},{},{}", projectId, topic, toUsers, msg);
        MessageProducer producer = null;
        try {
            producer = create(topic);
            Message message;
            if (msg instanceof String) {
                message = session.createTextMessage((String) msg);
            } else if (msg instanceof byte[]) {
                message = session.createBytesMessage();
                ((BytesMessage) (message)).writeBytes((byte[]) msg);
            } else {
                message = session.createObjectMessage(msg);
            }
            message.setStringProperty("pid", projectId);
            if (toUsers.length > 0) {
                if (toUsers.length == 1)
                    message.setStringProperty("uid", toUsers[0]);
                else {
                    StringBuilder sb = new StringBuilder();
                    int iMax = toUsers.length - 1;
                    for (int i = 0; i <= iMax; i++) {
                        sb.append(toUsers[i]);
                        if (i < iMax)
                            sb.append(",");
                    }
                    message.setStringProperty("uid", sb.toString());
                }
            }
            producer.send(message);
        } catch (JMSException e) {
            if (log.isErrorEnabled())
                log.error("send message", e);
            throw new RuntimeException(I18N.getLabel("easyplatform.message.publish.error", e.getMessage()));
        } finally {
            try {
                producer.close();
            } catch (JMSException e) {
            }
        }
    }

    private MessageProducer create(String topic) throws JMSException {
        if (connection == null) {
            if (log.isInfoEnabled())
                log.info("JMS connection created.");
            connection = connectionFactory.createConnection();
            connection.setExceptionListener(this);
            session = connection.createSession(false,
                    javax.jms.Session.AUTO_ACKNOWLEDGE);
        }
        MessageProducer producer = topic.toLowerCase().contains("queue") ? session.createProducer(session.createQueue(topic)) : session.createProducer(session.createTopic(topic));
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        producer.setDisableMessageID(true);
        producer.setDisableMessageTimestamp(true);
        return producer;
    }

    @Override
    public void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
            connection = null;
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
            session = null;
        }
        if (log.isInfoEnabled())
            log.info("JMS connection closed.");
    }

    @Override
    public void onException(JMSException e) {
        if (log.isErrorEnabled())
            log.error("onException", e);
        close();
    }
}
